package com.zjxf.service.impl;

import com.zjxf.base.bean.po.UmsUser;
import com.zjxf.base.bean.vo.VoUmsUser;
import com.zjxf.base.common.OperationException;
import com.zjxf.base.common.SysConst;
import com.zjxf.repository.UmsUserRepository;
import com.zjxf.service.UmsUserService;
import com.zjxf.utils.Digests;
import com.zjxf.utils.Encodes;
import com.zjxf.utils.UserUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

/**
 * created with IntelliJ IDEA
 *
 * @author: create by limu
 * Date: 2019/11/15
 * Time：16:55
 */
@Service
@AllArgsConstructor
@Transactional(rollbackOn = RuntimeException.class)
public class UmsUmsUserServiceImpl implements UmsUserService {

    private final UmsUserRepository umsUserRepository;

    @Override
    public Optional<UmsUser> findById(Long id) {
        return umsUserRepository.findByIdAndDeleteState(id, SysConst.DeleteState.UN_DELETE_STATE.getCode());
    }

    @Override
    public void addOrUpdate(VoUmsUser.addOrUpdate voUser) throws OperationException {
        Optional<UmsUser> userOptionalByUserName = umsUserRepository.findByUsernameAndDeleteState(voUser.getUsername(), SysConst.DeleteState.UN_DELETE_STATE.getCode());
        Optional<UmsUser> userOptionalById = umsUserRepository.findByIdAndDeleteState(voUser.getId(), SysConst.DeleteState.UN_DELETE_STATE.getCode());
        if (userOptionalByUserName.isPresent()) {
            throw new OperationException("该用户名已存在，请重新输入");
        } else {
            if (userOptionalById.isPresent()) {
                UmsUser umsUser = userOptionalById.get();
                String salt = Encodes.encodeHex(Digests.generateSalt(Digests.SALT_SIZE));
                umsUser.setSalt(salt);
                String encryptPassword = UserUtils.getEncryptPassword(voUser.getPassword(), salt);
                umsUser.setPassword(encryptPassword);
                umsUserRepository.save(umsUser);
            } else {
                UmsUser umsUser = new UmsUser();
                umsUser.setUsername(voUser.getUsername());
                String salt = Encodes.encodeHex(Digests.generateSalt(Digests.SALT_SIZE));
                umsUser.setSalt(salt);
                String encryptPassword = UserUtils.getEncryptPassword(voUser.getPassword(), salt);
                umsUser.setPassword(encryptPassword);
                umsUserRepository.save(umsUser);
            }
        }
    }

    @Override
    public void deleteUser(Long id) throws OperationException {
        UmsUser umsUser = this.findById(id).orElseThrow(() -> new OperationException("数据不存在或者已经被删除"));
        umsUser.setDeleteState(SysConst.DeleteState.UN_DELETE_STATE.getCode());
        umsUserRepository.save(umsUser);
    }

    @Override
    public Optional<UmsUser> findByUsernameAndDeleteState(String userName, Integer deleteState) {
        return umsUserRepository.findByUsernameAndDeleteState(userName, deleteState);
    }

}
